var ybDateFrom;
var ybDateTo;
$(function() {
	$("#" + tabId + " #depName").html(paramTabPage[tabId].pardepName);
	var param = $("#tabContent > .tab-pane.active").data();// 上一层页面传来的参数
	paramTabPage[tabId] = param;// 将上一个页面的值复制给这个页面
	ybDateFrom = param.dateFrom;
	ybDateTo = param.dateTo;
	$("[role='tabpanel']").each(function(i, n) {
		$(n).addClass('testCon');
	});
	$(document).ajaxStop(function() {

		// 备注的toptitle
		$('[data-toggle="yibao_fee_tooltip-drgs"]').mouseover(function(event) {
			$.justToolsTip({
				events : event,
				animation : "moveInTop",
				// width:"300px",
				contents : $(this).attr('remark_title'),
				gravity : 'top'
			});
		});
	})
	// 绘制科室病组tab布局
	drawTab_ul_div(paramTabPage[tabId].pardepCode);
	var quotas = [ {
		code : "FeeEff",
		name : "费用消耗指数",
		isLink : "0"
	}, {
		code : "CMI",
		name : "CMI值",
		isLink : "0"
	}, {
		code : "InCaseCnt",
		name : "入组病例数",
		isLink : "1"
	}, {
		code : "C_V",
		name : "变异系数",
		isLink : "0"
	}, {
		code : "ExcessCnt_F",
		name : "费用超标病例数",
		isLink : "1"
	},// 根据不同比较类型显示不同描述
	{
		code : "ExcessRatio_F",
		name : "费用超标病例率",
		isLink : "0"
	}, {
		code : "SpecificCnt_F",
		name : "费用特异病例数",
		isLink : "1"
	}, {
		code : "SpecificTaio_F",
		name : "费用特异病例率",
		isLink : "0"
	}, {
		code : "FeeEff_TF",
		name : "矫正费用消耗指数",
		isLink : "0"
	}, {
		code : "FeeEffContri",
		name : "费用消耗指数贡献度",
		isLink : "0"
	} ]

	var legend = [ paramTabPage[tabId].pardepName ];
	var xdata_2 = [];
	var seriesdata_2 = [];
	var ajaxCount = quotas.length * 3;
	getTableData(
			"Base",
			"dep",
			"hosp",
			function(data) {
				var columns = [];
				var datas = [];
				datas = datas.concat(data);
				concatTableData(
						quotas,
						datas,
						"depQuota_TimeEffFeeEff-table",
						columns,
						"dep",
						"hosp",
						function(table) {
							var param_t = jQuery.extend(true, {}, param);
							param_t.monitorType = "dep";
							getTrendData(
									param_t,
									"FeeEff",
									function(data_1) {
										var seriedata_2 = {
											type : "line",
											clickable : false,
											smooth : true,
											symbol : "none",
											name : paramTabPage[tabId].pardepName,
											data : []
										};
										for (o in data_1) {
											xdata_2.push(data_1[o].ddesc);
											seriedata_2.data
													.push(data_1[o].QuotaValue ? data_1[o].QuotaValue
															: 0);
										}
										seriesdata_2.push(seriedata_2);
										// 初始化科室和病组
										loadTrendChart("费用消耗指数", xdata_2,
												seriesdata_2, legend, $("#"
														+ tabId
														+ " #lineChart-2"));
										loadTrendChart("费用消耗指数", xdata_2,
												seriesdata_2, legend, $("#"
														+ tabId
														+ " #lineChart-4"));
									})
						});

			})
	/**
	 * 加载主诊组
	 */
	getTableData(
			"Base",
			"clinic",
			"dep",
			function(data) {
				var columns = [ {
					"data" : "ddesc"
				} ];
				var datas = [];
				datas = datas.concat(data);
				concatTableData(
						quotas,
						datas,
						"groupTable-table",
						columns,
						"clinic",
						"dep",
						function(table, oSetting) {
							var seriesdata_2_copy = jQuery.extend(true, [],
									seriesdata_2);
							var legend_copy = jQuery.extend(true, [], legend);
							var aoData = oSetting.aoData;
							table
									.find("tbody tr")
									.each(
											function(i, n) {
												$(n).find("td:last a").unbind();
												$(n)
														.find("td:last a")
														.click(
																function() {
																	if ($(
																			"#"
																					+ tabId
																					+ " #lineChart-2 img")
																			.size() > 0
																			|| $(
																					"#"
																							+ tabId
																							+ " #lineChart-2 img")
																					.size() > 0)
																		return;
																	var rowIndex = $(
																			this)
																			.attr(
																					"data-rowindex");
																	if (seriesdata_2_copy.length <= 0)
																		seriesdata_2_copy = jQuery
																				.extend(
																						true,
																						[],
																						seriesdata_2);
																	var aData = aoData[rowIndex]._aData;
																	var ccode = aData.ccode;
																	var ddesc = aData.ddesc;
																	if ($(this)
																			.find(
																					"i")
																			.hasClass(
																					"trend-link")) {
																		$(
																				"#"
																						+ tabId
																						+ " #lineChart-2")
																				.html(
																						'<img src="images/pageloading.gif" />');
																		array_remove(
																				legend_copy,
																				ddesc);
																		array_removeAttr(
																				seriesdata_2_copy,
																				"name",
																				ccode);
																		loadTrendChart(
																				"费用消耗指数",
																				xdata_2,
																				seriesdata_2_copy,
																				legend_copy,
																				$("#"
																						+ tabId
																						+ " #lineChart-2"));
																		$(this)
																				.find(
																						"i")
																				.removeClass(
																						"trend-link");
																	} else {
																		$(
																				"#"
																						+ tabId
																						+ " #lineChart-2")
																				.html(
																						'<img src="images/pageloading.gif" />');
																		var param_t = jQuery
																				.extend(
																						true,
																						{},
																						param);
																		param_t.monitorType = "clinic";
																		param_t.pargroupName = ccode;
																		legend_copy
																				.push(ddesc);

																		getTrendData(
																				param_t,
																				"FeeEff",
																				function(
																						data_1) {
																					var seriedata_1 = {
																						type : "line",
																						smooth : true,
																						symbol : "none",
																						name : ccode,
																						data : []
																					};
																					for (o in data_1) {
																						seriedata_1.data
																								.push(data_1[o].QuotaValue ? data_1[o].QuotaValue
																										: 0);
																					}
																					seriesdata_2_copy
																							.push(seriedata_1);
																					loadTrendChart(
																							"费用消耗指数",
																							xdata_2,
																							seriesdata_2_copy,
																							legend_copy,
																							$("#"
																									+ tabId
																									+ " #lineChart-2"));
																				})
																		$(this)
																				.find(
																						"i")
																				.addClass(
																						"trend-link");
																	}
																})
											})
							table.find("i.trend-link").click();
						});
			})
	getTableData(
			"Base",
			"drgs",
			"dep",
			function(data) {
				var columns = [ {
					"data" : "ccode",
					render : function(obj, type, full) {
						return '<span title="' + full.ddesc + '">' + full.ccode
								+ '</span>';
					}
				} ];
				var datas = [];
				datas = datas.concat(data);
				concatTableData(
						quotas,
						datas,
						"drgsTable-table",
						columns,
						"drgs",
						"dep",
						function(table, oSetting) {
							var seriesdata_2_copy = jQuery.extend(true, [],
									seriesdata_2);
							var legend_copy = jQuery.extend(true, [], legend);
							var aoData = oSetting.aoData;
							table
									.find("tbody tr")
									.each(
											function(i, n) {
												$(n).find("td:last a").unbind();
												$(n)
														.find("td:last a")
														.click(
																function() {
																	var rowIndex = $(
																			this)
																			.attr(
																					"data-rowindex");
																	if (seriesdata_2_copy.length <= 0)
																		seriesdata_2_copy = jQuery
																				.extend(
																						true,
																						[],
																						seriesdata_2);
																	var aData = aoData[rowIndex]._aData;
																	var ccode = aData.ccode;
																	if ($(this)
																			.find(
																					"i")
																			.hasClass(
																					"trend-link")) {
																		$(
																				"#"
																						+ tabId
																						+ " #lineChart-4")
																				.html(
																						'<img src="images/pageloading.gif" />');
																		array_remove(
																				legend_copy,
																				ccode);
																		array_removeAttr(
																				seriesdata_2_copy,
																				"name",
																				ccode);
																		loadTrendChart(
																				"费用消耗指数",
																				xdata_2,
																				seriesdata_2_copy,
																				legend_copy,
																				$("#"
																						+ tabId
																						+ " #lineChart-4"));
																		$(this)
																				.find(
																						"i")
																				.removeClass(
																						"trend-link");
																	} else {
																		$(
																				"#"
																						+ tabId
																						+ " #lineChart-4")
																				.html(
																						'<img src="images/pageloading.gif" />');
																		var param_t = jQuery
																				.extend(
																						true,
																						{},
																						param);
																		param_t.monitorType = "drgs";
																		param_t.pardrgCode = ccode;
																		legend_copy
																				.push(ccode);

																		getTrendData(
																				param_t,
																				"FeeEff",
																				function(
																						data_1) {
																					var seriedata_avgfee = {
																						type : "line",
																						smooth : true,
																						symbol : "none",
																						name : ccode,
																						data : []
																					};
																					for (o in data_1) {
																						seriedata_avgfee.data
																								.push(data_1[o].QuotaValue ? data_1[o].QuotaValue
																										: 0);
																					}
																					seriesdata_2_copy
																							.push(seriedata_avgfee);
																					loadTrendChart(
																							"费用消耗指数",
																							xdata_2,
																							seriesdata_2_copy,
																							legend_copy,
																							$("#"
																									+ tabId
																									+ " #lineChart-4"));
																				})
																		$(this)
																				.find(
																						"i")
																				.addClass(
																						"trend-link");
																	}
																});
											});
							table.find("i.trend-link").click();
						});
			})

	// 将指标与数据拼接成datatables要输出的格式
	function concatTableData(newQuotas, datas, divId, columns, monitorType,
			specHeader, callback) {
		var thead = $("#" + tabId + " #" + divId + " thead tr");
		for ( var o in newQuotas) {
			var quota = newQuotas[o];
			if (quota.code == "FeeEffContri") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='各单元内病例总体费用消耗贡献值,各单元费用消耗指数贡献度之和等于它们上级总体的费用消耗指数'>[注]</span></td>");
			} else if (quota.code == "C_V") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='病例费用消耗指数离散程度的大小'>[注]</span></td>");
			} else if (quota.code == "ExcessCnt_F") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='平均住院日超标的病例(超年度标杆)'>[注]</span></td>");
			} else if (quota.code == "ExcessCnt_TF") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='平均住院日或次均费用超标的病例(超年度标杆)'>[注]</span></td>");
			} else if (quota.code == "SpecificCnt_TF") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='平均住院日超过1.2*时间消耗指数*平均住院日标杆的病例 或者 次均费用>1.2*费用消耗指数*次均费用标杆的病例'>[注]</span></td>");
			} else if (quota.code == "SpecificCnt_F") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='次均费用>1.2*费用消耗指数*次均费用标杆的病例'>[注]</span></td>");
			} else if (quota.code == "TimeEff_TF") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='排除特异病例后的时间消耗指数'>[注]</span></td>");
			} else if (quota.code == "FeeEff_TF") {
				thead
						.append("<td style='width:50px;'>"
								+ quota.name
								+ "<span style='color: #0072ff;'  data-toggle='yibao_fee_tooltip-drgs' remark_title='排除特异病例后的费用消耗指数'>[注]</span></td>");
			} else {
				thead.append("<td style='width:50px;'>" + quota.name + "</td>");
			}
		}
		var i = 0;
		configQuotaFlag(newQuotas[i].code, newQuotas[i].name, i, newQuotas,
				newQuotas[i].isLink);
		// 对非基础指标列进行拼接，用递归方法解决循环与多个ajax请求异步问题
		function configQuotaFlag(value, name, cnt, array, isLink) {
			// 对有病例明细的列添加链接
			if (isLink == "1") {
				columns.push({
					"data" : value,
					"sType" : "number-html",
					"render" : function(obj, type, full) {
						if (full[value] == "0") {
							return "0";
						}
						return "<a href=\"javascript:loadCaseDtl('"
								+ full.ddesc + "|" + name + "','" + full.ccode
								+ "','" + monitorType + "', '" + value
								+ "')\">" + (full[value] ? full[value] : "")
								+ "</a>";
					},
				});
			} else {
				if (value == "FeeEffContri") {
					columns.push({
						"data" : value,
						"visible" : false
					});
				} else {
					columns.push({
						"data" : value,
						"visible" : true
					});
				}
			}
			getTableData(value, monitorType, specHeader, function(data,
					quotaCode) {
				var data_s = [];
				data_s = data_s.concat(data);
				mergeListcc(datas, data_s, 'ccode', '', quotaCode)
				ajaxCount--;
			})
			if (cnt + 1 < array.length) {
				configQuotaFlag(array[cnt + 1].code, array[cnt + 1].name,
						cnt + 1, array, array[cnt + 1].isLink);
			} else
				return false;
		}

		var timer = setInterval(
				function() {
					if (ajaxCount == 0) {
						clearInterval(timer);
						if (monitorType != "dep") {
							thead.append("<td>操作</td>");
							var operationColumn = {
								"data" : "OPERATION",
								"render" : function(obj, type, full, meta) {
									var trendClass = "";
									if (monitorType == "dep") {
										trendClass = " trend-link";
									}
									return "<div><a class='tr' title='趋势' data-rowindex='"
											+ meta.row
											+ "' ><i class='fa fa-line-chart"
											+ trendClass + "'></a></i></div>";
								}
							}
							columns.push(operationColumn);
						}
						var sorti = columns.length - 2;
						var tableTitle = $('#' + tabId + ' #' + divId).find(
								".contaotalsccq").text();
						var drawCallback = function(oSettings) {
							// 获取datatables标题,供导出时获取
							oSettings.expertName = this.find(".contaotalsccq")
									.text();
							var table = $('#' + divId);
							callback(table, oSettings);
						}
						var paramsDataTables = {
							lengthChange : false,
							info : false,
							searching : false,
							order : [ [ sorti, "desc" ] ],
							tableTitle : tableTitle
						};
						paramsDataTables.drawCallback = drawCallback;
						if (monitorType == "dep") {
							paramsDataTables["ordering"] = false;
						}
						if (monitorType == "drgs") {
							paramsDataTables["scrollY"] = "300px";
						} else if (monitorType == "clinic") {
							paramsDataTables["scrollY"] = "400px";
						}
						$("#" + tabId + " #" + divId).dataTableBasic(columns,
								datas, paramsDataTables);
						if (monitorType == "drgs") {
							$('.testCon').each(function(i, n) {
								$(n).removeClass('testCon');
							});
						}
					}
				}, 500);
	}

	// 根据指标发送请求获取数据
	function getTableData(quotaCode, monitorType, specHeader, callback) {
		var p1 = drgUI.setAjaxData(tabId);
		p1.isGetCc = "0";
		p1.specHeader = specHeader;
		p1.quotaCode = quotaCode;
		p1.monitorType = monitorType;
		p1.compareType = "std";
		p1.dateFrom = ybDateFrom;
		p1.dateTo = ybDateTo;
		$.post(contextPath + "/DrgsIndexCal/indexCal.dhc", p1).done(
				function(data) {
					var data = data.data;
					callback(data, quotaCode);
				})
	}

	// 获取双指标趋势数据
	function getTrendData(param_t, quotaCode, callback) {
		param_t.quotaCode = quotaCode;
		param_t.mrType = paramTabPage[tabId].mrType;
		param_t.dateFrom = ybDateFrom;
		param_t.dateTo = ybDateTo;
		$.post(contextPath + "/ywcHome/getCMIDRGCount.dhc", param_t).done(
				function(data) {
					var data = data.data;
					callback(data, quotaCode);
				})
	}

	function loadTrendChart(title, xdata, seriesdata, legend, container) {
		// 调公共方法组装数据
		var lines = [];
		var echartData = [];
		for ( var o in legend) {
			lines.push({
				code : 'code' + o,
				desc : legend[o],
				data : []
			});
		}
		for ( var o in seriesdata) {
			var obj = [];
			for ( var j in seriesdata[o].data) {
				var temp = {};
				temp.ddesc = xdata[j];
				temp['code' + o] = seriesdata[o].data[j];
				obj.push(temp);
			}
			echartData.push(obj);
		}
		var chartParams = {
			legendPosition : 'bottom'
		};
		lineChartBasic(container, lines, echartData, title + '变化趋势', '',
				chartParams);
	}
});
/**
 * 
 * @@param depCode
 * @@returns
 * @any @ Discription:拼接科室和病组tab页布局
 * @costConsumptionIndex.js
 */
function drawTab_ul_div(depCode) {
	var Tab_id = new Base64().encode(depCode)
	var str = '<ul class="nav nav-tabs tabconulcq" role="tablist">';
	str += '<li role="presentation" class="active" style="margin-right: 20px;"><a href="#'
			+ Tab_id
			+ 'depTimeEffFeeEff_Clinic" role="tabpanel" data-toggle="tab">主诊组</a></li>';
	str += '<li role="presentation"><a href="#'
			+ Tab_id
			+ 'depTimeEffFeeEff_Drgs" role="tabpanel" data-toggle="tab">病组</a></li>';
	str += '</ul>';
	$('#' + tabId + ' #tab_ul').html(str);
	str = '  <div role="tabpanel" class="tab-pane active" id="' + Tab_id
			+ 'depTimeEffFeeEff_Clinic"> ';
	str += '<div class="row">';
	str += '<div class="col-xs-4">';
	str += '<div class="" id="lineChart-2" style="width: 425px; height: 255px;"><img src="images/pageloading.gif" /></div>';
	str += '</div>';
	str += '<div class="col-xs-8">';
	str += '<div id="groupTable">';
	str += '<table id="groupTable-table" class="table table-striped" style="width: 720px;">';
	str += '<thead><tr><td style="width: 30px;">主诊组</td></tr></thead>';
	str += '<tbody></tbody> ';
	str += '</table>';
	str += '</div> </div></div> </div>';

	str += '<div role="tabpanel" class="tab-pane" id="' + Tab_id
			+ 'depTimeEffFeeEff_Drgs">';
	str += '<div class="row">';
	str += '<div class="col-xs-4">';
	str += '<div class="paddingd10" id="lineChart-4" style="width: 425px; height: 255px;"> <img src="images/pageloading.gif" /> </div>';
	str += '</div>';
	str += '<div class="col-xs-8">';
	str += '<div id="drgsTable">';
	str += '<table id="drgsTable-table" class="table table-striped" style="width: 720px;">';
	str += '<thead><tr><td style="width: 30px;">病组</td></tr></thead>';
	str += '<tbody></tbody>';
	str += '</table>';
	str += '</div></div></div></div>';
	$('#' + tabId + ' #tab-content_dep_drgs').html(str);

};
function loadCaseDtl(title, ccode, monitorType, quotaCode) {
	var param = drgUI.setAjaxData(tabId);
	param.caseLinkCode = quotaCode;
	if (ccode) {
		if (monitorType == "depGroup") {// 兼容多科室的问题
			param.depCode = "";// 科室code 置为空
			if (ccode.indexOf(",") > -1) {
				param.deps = ccode;
			} else {
				param.depGroupCode = ccode;
			}
		} else if (monitorType == "dep") {
			param.pardepCode = ccode;
		} else if (monitorType == "ward") {
			param.parwardCode = ccode;
		} else if (monitorType == "clinic") {
			param.pargroupName = ccode;
		} else if (monitorType == "protomedicus") {
			param.protomedicus = ccode;
		} else if (monitorType == "physician") {
			param.physician = ccode;
		} else if (monitorType == "resident") {
			param.resident = ccode;
		} else if (monitorType == "mdc") {
			param.parmdcCode = ccode;
		} else if (monitorType == "adrg") {
			param.paradrgCode = ccode;
		} else if (monitorType == "drgs") {
			param.pardrgCode = ccode;
		}
	}
	param.compareType = "std";
	ccode = ccode.replace(/,/g, "")// 多科室的时候去掉字符串中的, 不然打不开页面
	openTab('/pages/drgscommon/case.jsp', title + "|" + "病例明细", "caseDtl"
			+ monitorType + ccode + quotaCode, "caseDtl" + monitorType + ccode
			+ quotaCode, param);
};
